package org.example.captchademo.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.util.StringUtil;
import org.example.captchademo.Model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    private static long VALID_TIME = 60 * 1000;`

    @RequestMapping("/get")
    private void getCaptcha(HttpSession session,HttpServletResponse response){
//        ICaptcha captcha = CaptchaUtil.createLineCaptcha(100, 50);
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        try {
            captcha.write(response.getOutputStream());
//        前端很容易有缓存，所以后端要设置禁止缓存
            response.setHeader("Pragma", "No-cache");
//            设置返回格式
            response.setContentType("image/jpeg");
//            打印验证码
            System.out.println(captcha.getCode());
//            存储session
//            session.setAttribute("CAPTCHA_SESSION_CODE", captcha.getCode());
//            session.setAttribute("CAPTCHA_SESSION_DATE", System.currentTimeMillis());
            session.setAttribute(captchaProperties.getSession().getCode(), captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
//        Servlet的OutputStream记得自行关闭哦！
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

   @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session){
//        参数校验   实在framework包里的
       if (!StringUtils.hasLength(captchaCode)){
           return false;
       }
//       判断用户输入验证码是否和session一致
//       String sessionCode = (String) session.getAttribute("CAPTCHA_SESSION_CODE");
       String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
       Long sessionDate = (Long) session.getAttribute(captchaProperties.getSession().getDate());
//       是否在有效期内     使用包装类
       if (captchaCode.equalsIgnoreCase(sessionCode)
               && sessionDate!=null
               && (System.currentTimeMillis()-sessionDate) < VALID_TIME){
           return true;
       }
       return false;
    }
}
